package com.rj.framework.validation;

import com.rj.framework.context.Context;
import jakarta.validation.ConstraintValidator;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

/**
 * 支持上下文注入的验证器基类
 */
public abstract class ContextAwareValidator<A extends Annotation, T> implements ConstraintValidator<A, T>, ValidatableContext {

    private Context context;
    private Map<String, Object> currentParameters;


    // 在initialize中获取参数
    @Override
    public void initialize(Annotation constraintAnnotation) {
        if (constraintAnnotation instanceof ContextAwareValidation) {
            ContextAwareValidation cav = (ContextAwareValidation) constraintAnnotation;
            currentParameters = getParametersFromAnnotation(cav);
        }
    }

    private Map<String, Object> getParametersFromAnnotation(ContextAwareValidation cav) {
        Map<String, Object> params = new HashMap<>();
        for (Param param : cav.params()) {
            params.put(param.key(), param.value());
        }
        return params;
    }

    @Override
    public Map<String, Object> getParameters() {
        return currentParameters;
    }
    @Override
    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }
}